import cgi
import datetime
import logging
import urllib

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch

import appengine_admin

from xml.etree.ElementTree import parse, fromstring, XML
#from xml.dom.minidom import parse, parseString

from django.utils import simplejson as json 

#from Crypto.Hash import SHA256
import hashlib

from adminmodels import *
from models import *

salt = '3Eb7k'
logging.getLogger().setLevel(logging.DEBUG)

"""
the models are defined in the models.py file
the admin models are defined in the adminmodels.py file

"""

"""
code to implement rest interface
"""

"""
	registering the admin models
"""

appengine_admin.register(AdminGauser, 
			 AdminGabusiness, 
			 AdminGaevent, 
			 AdminGabizlocation, 
	   		 AdminGaeventlocation, 
			 AdminGauserfriend,
			 AdminGauserinbox,
			 AdminGauseraddedevent,
			 AdminGauseraddedbusiness,
			 AdminGauserlocation,
			 AdminGaeventimages,
			 AdminGaeventvideo,
			 AdminGacategory,
			 AdminGaeventcategory,
			 AdminGauserassociation,
                         AdminGaeventrecommendation,
			 AdminGausernotificationtypes,
			 AdminGausernotification,
			 AdminGabusinesstype,
			)

"""
	page stuff
"""

months = {1:'Jan',
	  2:'Feb',
	  3:'Mar',
	  4:'Apr',
	  5:'May',
	  6:'Jun',
	  7:'Jul',
	  8:'Aug',
	  9:'Sep',
	  10:'Oct',
	  11:'Nov',
	  12:'Dec',
	  }


def str2bool(v):
  return v.lower() in ("yes", "true", "t", "1")
  
class MainPage(webapp.RequestHandler):
    def get(self):
        url = users.create_logout_url(self.request.uri)
	"""
	categorylist= {'Sports':1, 'Basketball':3, 'Football':4, 
           'Baseball':2, 'Music':5, 'Hip Hop':10, 
           'Pop':9, 'Cuisine':6, 'Korean':7,
           'Chinese':8}
	"""
	categoryrequest = self.request.get(u'category') or 0

        """
	this is showing the categories for the wesite... sorted by categoryname
	    1. each category name should send a request to the website with category id as query string... it will sort events displayed
        """
	categories = Gacategory.all().order('categoryname')
	self.response.out.write("<a href='/home'><h2>Categories</h2> </a>")
        for category in categories:
                if category.categoryparentname == None:
		    if category.key().id() != int(categoryrequest):
		        self.response.out.write("<font size='4'><a href='/home?category=%s'> %s </a> </font><br>" % (category.key().id() , category.categoryname) )
		    else:
			self.response.out.write("<font size='4'><a href='/home?category=%s'><b> %s </b></a> </font><br>" % (category.key().id() , category.categoryname) )
                    for each in category.subcategories.order('categoryname'):
			if each.key().id() != int(categoryrequest):
		            self.response.out.write("&nbsp; &nbsp; &nbsp;<font size='3'><a href='/home?category=%s'> %s </a></font><br>" % (each.key().id() ,each.categoryname, ) )
			else:
			    self.response.out.write("&nbsp; &nbsp; &nbsp;<font size='3'><a href='/home?category=%s'> <b>%s </b></a></font><br>" % (each.key().id() ,each.categoryname, ) )

     
	
        query_str1 = "SELECT * FROM Gauser ORDER BY date_created DESC LIMIT 10"
        gausers = db.GqlQuery (query_str1)

	query_str2 = "SELECT * FROM Gabusiness ORDER BY date_created DESC LIMIT 10"
        gabizs = db.GqlQuery (query_str2)	

	
	query_str3 = "SELECT * FROM Gaevent ORDER BY eventstartdate ASC LIMIT 10"
        gaevents = db.GqlQuery (query_str3)

	eventkeys = []

	"""
	this picks the events that fit the category given in teh querystring... this is picked from categories that are shown
	"""

	if categoryrequest:
	    cat_info = Gacategory.get_by_id(int(categoryrequest))
	    subcat_info = cat_info.subcategories
	    if subcat_info.count():
		for subcat in subcat_info:
	            subcatevents = subcat.categorys_events
	   	    eventkeys.extend([Gaeventcategory.gaevent.get_value_for_datastore(cat) for cat in subcatevents])		    
	    else:
	        catevents = cat_info.categorys_events
	        eventkeys.extend([Gaeventcategory.gaevent.get_value_for_datastore(cat) for cat in catevents])
	    gaevents = Gaevent.get(eventkeys)
	else:
            gaevents = db.GqlQuery (query_str3)


	self.response.out.write("<h2>Created Events</h2>" )
        if gaevents:
	    for gaevent in gaevents:
                if gaevent.eventstartdate:
	            startdate = gaevent.eventstartdate
	            self.response.out.write("%d/%d/%d &nbsp; &nbsp; &nbsp;  %s <br>" % (startdate.month, startdate.day, startdate.year,  gaevent.eventname) )
                else:
                    self.response.out.write("&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; %s <br/>" % (gaevent.eventname) )
        else:
	    cat_info = Gacategory.get_by_id(int(categoryrequest))
	    if categoryrequest:
	        self.response.out.write(" No Events for %s" % cat_info.categoryname  )
	    else:
		self.response.out.write(" No Events")

	self.response.out.write("<h2>Most Recently Created Users</h2>" )
        
        for gauser in gausers:
	    self.response.out.write("<div>%s</div>" % (gauser.email) )
	    #self.response.out.write("<div><a href='/user/id/%d'> %s </a></div>" % (gauser.key().id(), gauser.email))
        #self.response.out.write(" <br /><a href='/home/user'>register more users...</a>")

	self.response.out.write("<h2>Most Recently Created Bizs</h2>" )
	for gabiz in gabizs:
	    self.response.out.write("<div> %s </div>" % gabiz.bizname)

        self.response.out.write("""
<br/>
<br/>     
<a href='/admin'><h2>Click here to add data</h2></a> <br/></div>
"""
	)
	self.response.out.write("<a href=%s>Logout</a>"% url)

        self.response.out.write( "</body></html>")


class UserProfile(webapp.RequestHandler):
    def get(self):
        #upload_url = blobstore.create_upload_url('/user/register')
	upload_url = '/user/register'
        self.response.out.write('<html><body>')
	self.response.out.write('<h4>Register User</h4>')

        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""
<div align="center">
<table>
<tr>
  <td> Email </td>
  <td> <input type="text" name="email" > </td>
</tr>
<tr>
  <td> First Name</td>
  <td> <input type="text" name="firstname" > </td>
</tr>
<tr>
  <td> Last Name </td>
  <td> <input type="text" name="lastname" > </td>
</tr>
<tr>
  <td> Password</td>
  <td> <input type="password" name="password" > </td>
</tr>
<tr>
  <td> Current Zip </td>
  <td> <input type="text" name="currentzip" > </td>
</tr>
<tr>
  <td> Gender </td>
  <td> 
      <input type="radio" name="gender" value="Male" /> Male
      <input type="radio" name="gender" value="Female" /> Female
  </td>
</tr>
<tr>
  <td> Birthday </td>
  <td> <select name="month" >
"""
        )
        for i in range(1,len(months)+1):
            self.response.out.write(
"""
           <option value="%d">%s</option>"""  % (i, months[i] )
            )
        self.response.out.write(
""" 
       </select>
       <select name="date">
"""     
        ) 
        for i in range(1,32):
            self.response.out.write(
"""
           <option value="%d">%d</option>"""  % (i, i )
            )
        self.response.out.write(
""" 
       </select>
       <select name="year">
"""     
        )  
	currentyr = datetime.datetime.now().year
        for i in range(1,120):
            self.response.out.write(
"""
           <option value="%d">%s</option>"""  % (currentyr-i, currentyr-i)
            )
        self.response.out.write(
""" 
       </select>
"""     
        )        
        self.response.out.write("""
  </td>
</tr>
<tr>
  <td> Username </td>
  <td> <input type="text" name="username" > </td>
</tr>
<tr>
  <td> Public</td>
  <td> <input type="checkbox" name="is_public" value="True">   </td>
</tr>
<tr>
  <td> Share Calendar </td>
  <td> <input type="checkbox" name="is_calendar_shared" value="True">  </td>
</tr>
<tr>
  <td> Image </td>
  <td> <input type="file" name="image">  </td>
</tr>
</table>
</div>

<input type="submit" name="submit" value="Submit"> 
</form></body></html>""" )

"""
#creation for blobstore
class UserCreationPage(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        header = self.request.headers['Content-Type']
	body = self.request.body


	upload_files = self.get_uploads()  # 'file' is file upload field in the form
	blob_info1 = upload_files[0]

	
	#need to add something to say if it was successful or failed
	

	#this could be any type of form
        if "multipart/form-data" in header:
	    reqemail = self.request.get('email')
	    reqfirstname = self.request.get('firstname')
	    reqlastname = self.request.get('lastname')
	    reqcurrentzip = self.request.get('currentzip')
	    reqgender = str(self.request.get('gender'))
	    reqbirthday = datetime.date(1990, 03, 13), #birthday[i].text, convert it to dateself.request.get('birthday'),
	    requsername = self.request.get('username')
	    reqpassword = self.request.get('password')	

	    if  not reqpassword or not reqemail or not reqfirstname or not reqlastname or not reqcurrentzip or not reqgender or not reqbirthday or not requsername:
	        self.redirect('/home/user')
	        return	    




	    user = Gauser(      email = reqemail,
			        firstname = reqfirstname,
			        lastname = reqlastname,
			        currentzip = reqcurrentzip,
			        gender = reqgender,
			        birthday = reqbirthday, #birthday[i].text, convert it to dateself.request.get('birthday'),
			        username = requsername,
			        password = reqpassword,
			        
	    )
	    user.is_public = str2bool(self.request.get('is_public'))
	    user.is_calendar_shared = str2bool(self.request.get('is_calendar_shared'))

	    user.image = blob_info1.key()

	    #viewing blobstore images in image src takes loading time

	    #img = images.Image(blob_key= str(blob_info1.key()) )
	    #img.resize(height=60,) 
	    #thumbnailimg = img.execute_transforms(output_encoding = images.PNG)

	    #user.thumbnail = thumbnailimg
	    user.put()
	 
	    #try:
	    #    user.put()      
  	    #except ValueError: 
		#self.redirect('/home')
		#return
	
	    self.redirect('/home')
	    return

	if "text/xml" in header:
	    # do some xml parsing of user
	    parsed = fromstring(body)
	    reqfirstname = parsed.findall('firstname')[0].text
	    reqlastname = parsed.findall('lastname')[0].text
	    reqemail = parsed.findall('email')[0].text
	    reqgender = parsed.findall('gender')[0].text
	    reqcurrentzip = parsed.findall('currentzip')[0].text
	    requsername = parsed.findall('username')[0].text
	    reqbirthday = parsed.findall('birthday')[0].text
	    reqpassword = parsed.findall('password')[0].text
	    reqis_public = parsed.findall('is_public')[0].text
	    reqis_calendar_shared = parsed.findall('is_calendar_shared')[0].text
	


	    
	    #for i in range(0, 1):   
    		#user = Gauser(  email = email[i].text,
		#	    	firstname = firstname[i].text,
		#	   	lastname = lastname[i].text,
		#	    	currentzip = currentzip[i].text,
		#	    	gender = gender[i].text,
		#	    	birthday = datetime.date(1990, 03, 13), #birthday[i].text, convert it to date
		#	    	username = username[i].text,
		#	    	password = password[i].text,
		#	    	is_public = str2bool(is_public[i].text),
		#	    	is_calendar_shared = str2bool(is_calendar_shared[i].text),
		#)
	    
	    if  not reqpassword or not reqemail or not reqfirstname or not reqlastname or not reqcurrentzip or not reqgender or not reqbirthday or not requsername:
		#or do seomthing else since not all fields were filled	        
		self.redirect('/home/user')
	        return	    
   
	    user = Gauser(  email = reqemail,
			    firstname = reqfirstname,
			    lastname = reqlastname,
			    currentzip = reqcurrentzip,
			    gender = reqgender,
			    birthday = datetime.date(1990, 03, 13), #birthday[i].text, convert it to date
			    username = requsername,
			    password = reqpassword,
			    is_public = str2bool(reqis_public),
			    is_calendar_shared = str2bool(reqis_calendar_shared),
		)

	    user.put()
	    self.redirect('/home')
	    return
        self.redirect('/home')
	return

"""


"""
class UserLogin(webapp.RequestHandler):
    def post(self):
	header = self.request.headers['Content-Type']
	body = self.request.body
	self.response.headers['Content-Type'] = "text/xml"
        salt = '3Eb7k'
        if "multipart/form-data" in header:
		parsed = fromstring(body)
		reqemail = self.request.get('email')
		requsername = self.request.get('username')
	        hashpwd = hashlib.sha256.new(salt + str(self.request.get('password')))
		#query_str1 = "SELECT * FROM Gauser WHERE username = %s ORDER BY date_created DESC LIMIT 10"
		gauser = Gauser.all().filter('username =', requsername).get()
		if gauser.password == hashpwd:
		    #so something for sign in... cookies or session start
	
"""

#viewing user data
class UserPage(webapp.RequestHandler):
    def get(self, ID):
        user= Gauser.get_by_id(int(ID))

        self.response.out.write('<html><body>')
	self.response.out.write('<h4>%s</h4>' % user.email)
        if user != None:
            self.response.out.write(
"""
	id: %s <br />
	username: %s <br />
	email: %s <br />
	firstname:%s <br />
	lastname:%s <br />
	currentzip:%s <br />
	gender:%s <br />
	birthday:%s <br />
	is_active:%s <br />
	is_public:%s <br />
	is_calendar_shared:%s <br />

""" % (user.key().id(), user.username, user.email, user.firstname, user.lastname, user.currentzip, user.gender, user.birthday, user.is_active, user.is_public, user.is_calendar_shared,  )
            )

            if user.image:
	        self.response.out.write(" <img src='/img?img_id=%s'></img> " % user.key())

	
	    if (user.user_associations).count() :
                self.response.out.write("<h3>Associations</h3><br />")
                for association in user.user_associations:	    
                    self.response.out.write(
"""
		associationtype:%s <br />
		associationid:%s <br />
""" % (association.associationtype, association.associationid)
            	     )

	    if (user.user_locations).count():
  	        self.response.out.write("	<h3>savedlocations</h3><br />")
                for location in user.user_locations:
	    	    self.response.out.write(
"""
	    <h4>Location</h4>
	        is_primary:%s<br />
		geocode:%s<br />
		address:%s<br />
		city:%s<br />
		state:%s<br />
		zip:%s<br />
		country:%s<br />
""" % (location.is_primary, location.geopoint, location.address, location.city, location.state, location.zipcode, location.country)
		    )

	self.response.out.write('</html></body>')

#db.blob image viewer
class ImagePage (webapp.RequestHandler):
    def get(self):
        user = db.get(self.request.get("img_id"))
        #size = self.request.get(u"size")
        if user.image:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(user.image)
        else:
            self.response.out.write("No image")

#db.blob image viewer
class ImagePageExt (webapp.RequestHandler):
    def get(self):
        #user = db.get(self.request.get("img_id"))
	imagelink = ""
        result = urlfetch.fetch(imagelink)
        image = result.content     
	#size = self.request.get(u"size")
        if image:
            self.response.headers['Content-Type'] = "image/png"
	    resizedimage = images.resize( image, 400)
            self.response.out.write(resizedimage)
        else:
            self.response.out.write("No image")

"""
	url pattern stuff
"""

application = webapp.WSGIApplication([
    (r'^(/admin)(.*)$', appengine_admin.Admin),
    (r'^/?$', MainPage),
    (r'^/home/?$', MainPage),
    (r'^/home/user?$', UserProfile),
    (r'^/img', ImagePage),
    (r'^/user/id/([^/]+)?', UserPage),
], debug=True
)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
